package com.mco.socket.nio;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author ：liao.wei
 * @date ：2023/10/7 14:43
 * @package : com.mco.socket.read
 */
public class RedisServerNio {
	
	static ArrayList<SocketChannel> socketChannels = new ArrayList<>();
	static ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
	
	
	public static void main(String[] args) throws IOException {
		while (true) {
			System.out.println("模拟Redis server启动 -- 等待连接");
			ServerSocketChannel serverSocket = ServerSocketChannel.open();
			serverSocket.bind(new InetSocketAddress("127.0.0.1", 6688));
			//设置唯非阻塞
			serverSocket.configureBlocking(false);
			while (true) {
				for (SocketChannel channel : socketChannels) {
					int read = channel.read(byteBuffer);
					if (read > 0) {
						System.out.println("---正在读取数据---" + read);
						byteBuffer.flip();
						byte[] bytes = new byte[read];
						byteBuffer.get(bytes);
						System.out.println(new String(bytes));
						byteBuffer.clear();
					}
				}
				SocketChannel socketChannel = serverSocket.accept();
				if (socketChannel != null) {
					System.out.println("---成功连接---");
					socketChannel.configureBlocking(false);
					socketChannels.add(socketChannel);
					System.out.println("---socketChannels size:---====>" + socketChannels.size());
				}
			}
		}
	}
}
